package lion.web.interceptors.ipac;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lion.dev.web.WebUtil;
import lion.framework.core.conf.Config;
import lion.framework.core.conf.ConfigManager;
import lion.framework.core.web.request.RequestHandler;
import lion.framework.core.web.request.RequestInterceptor;
import lion.framework.core.web.views.JSPView;

import org.apache.commons.lang.StringUtils;

/**
 * IP Access Controll <br/>
 * IP访问控制 patterns:<br/>
 * 1、192.168.1.101<br/>
 * 2、192.168.1.*<br/>
 * 3、192.168.1.[30-45]<br/>
 *
 * <pre>
 * time   2013年8月1日
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion.dev
 */
public class IPACInterceptor implements RequestInterceptor {

	private String template = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />	<style>		body{background-color:#000;text-align:center;color:#70FE10;font-size:16px;}div{width:400px;margin:0 auto;margin-top:150px;border:solid 3px #FFA50F;font-size:32px;color:#FFA50F;font-weight:bold;font-family:arial,\"宋体\" ;text-align:center;padding:10px 20px;}</style></head><body><div>Access Denied</div><p>further information contact ${ServerAdmin}</p></body></html>";
	private String errorpage;

	private Config config;

	public IPACInterceptor() {

		config = ConfigManager.getConfig("framework");
		String serveradmin = config.getString("framework.serveradmin", "the webmaster");
		template = template.replace("${ServerAdmin}", serveradmin);
		this.errorpage = config.getString("framework.web.ipac.errorpage");
	}

	@Override
	public void intercept(HttpServletRequest request, HttpServletResponse response, RequestHandler rh) throws Exception {

		String ip = WebUtil.getRemoteIP(request);
		if (!IPACManager.isIPAllowed(rh.getPath(), ip)) {
			response.setStatus(403);

			if (StringUtils.isNotBlank(this.errorpage)) {
				new JSPView(this.errorpage).render(request, response);
			} else {
				response.setContentType("text/html");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(template);
			}
			return;
		}

		rh.handle(request, response);
	}

}
